package cn.buddha.jesj.thread.java;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author shihao
 * @description 线程计数器测试
 */
@Slf4j
public class CountdownTest {

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(2);

        ExecutorService executorService = Executors.newFixedThreadPool(2);

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    log.error("Thread-1 中断异常了", e);
                } finally {
                    log.info("Thread-1执行完成");
                    countDownLatch.countDown();
                }
            }
        });

        executorService.execute(() -> {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                log.error("Thread-2 中断异常", e);
            } finally {
                log.info("Thread-2 执行完成");
                countDownLatch.countDown();
            }
        });

        log.info("主线程等待子线程执行完毕");
        log.info("计数器当前值为：" + countDownLatch.getCount());

        try {
            countDownLatch.await(7000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            log.info("子线程执行异常");
        }

        log.info("计数器当前值为：" + countDownLatch.getCount());
        log.info("主线程执行完毕");
//        executorService.shutdown();
        executorService.shutdownNow();
    }

}
